package com.ark.task;

import com.ark.constant.OrderConstant;
import com.ark.entity.Orders;
import com.ark.mapper.OrderMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author dyz
 * @date 2025/4/12 18:25
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class OrderTask {

    private final OrderMapper orderMapper;
    /**
     * 处理超时订单
     * 每分钟触发一次
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        LocalDateTime now = LocalDateTime.now();
        log.warn("定时处理超时订单: {}", now);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(OrderConstant.PENDING_PAYMENT, now.minusMinutes(15));
        if(!ordersList.isEmpty()){
            ordersList.forEach(order -> {
                order.setStatus(OrderConstant.CANCELLED);
                order.setCancelReason("订单超时,自动取消!");
                order.setCancelTime(now);
            });
            orderMapper.updateById(ordersList);
        }
    }

    /**
     * 处理一直派送中的订单
     * 每天凌晨1点触发
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        LocalDateTime now = LocalDateTime.now();
        log.warn("定时处理派送中的订单: {}", now);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(OrderConstant.DELIVERY_IN_PROGRESS, now.minusHours(1));
        if(!ordersList.isEmpty()){

            ordersList.forEach(order -> {
                order.setStatus(OrderConstant.COMPLETED);
            });
            orderMapper.updateById(ordersList);
        }
    }
}
